package com.hxy.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hxy.tlias.mapper.EmpExprMapper;
import com.hxy.tlias.mapper.EmpMapper;
import com.hxy.tlias.pojo.*;
import com.hxy.tlias.service.EmpLogService;
import com.hxy.tlias.service.EmpService;
import com.hxy.tlias.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private EmpLogService empLogService;

    /**
     * 列表查询
     */
    public PageBean page(EmpQueryParam param) {
        //1设置分页参数 2调用方法 3封装放回
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Emp> empList = empMapper.list(param);
        Page p = (Page) empList;
        return new PageBean(p.getTotal(), p.getResult());
    }

    /**
     * 新增员工
     */
    @Transactional(rollbackFor = Exception.class)   //开启事务,rollbackFor指定处理所有异常，默认只能处理运行时异常
    @Override
    public void save(Emp emp) {
        try {
            emp.setPassword("123456");
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.insert(emp);

            Integer id = emp.getId();
            log.info("id={}", id);

            List<EmpExpr> exprList = emp.getExprList();
            if (!CollectionUtils.isEmpty(exprList)) {
                exprList.forEach((expr) -> {
                    expr.setEmpId(id);
                });
                empExprMapper.insertBatch(exprList);
            }
        } finally {
            //无论新增员工与否，都需增加日志
            EmpLog empLog = new EmpLog();
            empLog.setOperateTime(LocalDateTime.now());
            empLog.setInfo("插入员工信息：" + emp);
            empLogService.insertLog(empLog);
        }
    }

    @Transactional //开启事务，要删两个表的信息
    public void delete(List<Integer> ids) {
        //1删员工
        empMapper.deleteBatch(ids);
        //2删经历
        empExprMapper.deleteBatch(ids);
    }

    //员工修改-回显
    @Override
    public Emp getById(Integer id) {
        return empMapper.getById(id);
    }

    //员工修改
    @Transactional
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
        //先删后增
        empExprMapper.deleteByEmpId(emp.getId());
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach((expr) -> {
                expr.setEmpId(emp.getId());
            });
            empExprMapper.insertBatch(exprList);
        }
    }

    /**
     * 员工登录
     * @param emp
     * @return
     */
    @Override
    public EmpLoginInfo login(Emp emp) {
        //1.调用mapper查询
        Emp empDB = empMapper.selectUsernameAndPassword(emp);
        //2.判断用户密码是否正确
        if(empDB != null){
            //3.查到数据，构造返回值
            //生成jwt令牌

            //自定义有效载荷
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",empDB.getId());
            claims.put("username",empDB.getUsername());
            //调用jwt工具类，生成令牌
            String jwt = JwtUtils.generateJwt(claims);
            return new EmpLoginInfo(empDB.getId(), empDB.getUsername(), empDB.getName(), jwt);
        }

        return null;
    }
}
